package com.xyht.sca_s.student_manage_system.modules.salaryManagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.AppTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.RangeTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsRecordStatusEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.util.NewTipsUtil;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.SmsSalaryColumn;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.SmsSalaryColumnContent;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.SmsSalaryDetail;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.SmsSalaryTask;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.req.SmsSalaryColumnReq;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.req.SmsSalaryDetailReq;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.req.SmsSalaryTaskReq;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.entity.resp.*;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.mapper.SmsSalaryColumnContentMapper;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.mapper.SmsSalaryColumnMapper;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.mapper.SmsSalaryDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.mapper.SmsSalaryTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.salaryManagement.service.SmsSalaryTaskService;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsTeacherInfo;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsUserTeacherRelation;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsUserTeacherRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsSearchUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.CheckStatusConstant.CHECK_STATUS_ERROR;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.CheckStatusConstant.CHECK_STATUS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.DisplayStatusConstant.DISPLAY_STATUS_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.DisplayStatusConstant.DISPLAY_STATUS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.IsNoticeStatusConstant.NOTICE_STATUS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.salaryManagement.constant.PublishStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.student.constant.StudentInfoCommonConstant.PER_SHEET_NUM;

/**
 * <p>
 * 工资单发布任务表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-09-14
 */
@Service
public class SmsSalaryTaskServiceImpl extends ServiceImpl<SmsSalaryTaskMapper, SmsSalaryTask> implements SmsSalaryTaskService {
    @Autowired
    private SmsSalaryTaskMapper smsSalaryTaskMapper;
    @Autowired
    private SmsSalaryDetailMapper smsSalaryDetailMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private NewTipsUtil newTipsUtil;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsSalaryColumnMapper smsSalaryColumnMapper;
    @Autowired
    private SmsSalaryColumnContentMapper smsSalaryColumnContentMapper;
    @Autowired
    private SmsTeacherInfoMapper smsTeacherInfoMapper;
    @Autowired
    private SmsUserTeacherRelationMapper smsUserTeacherRelationMapper;


    @Override
    @Transactional
    public ResponseResult addSalaryTask(SmsSalaryTaskReq smsSalaryTaskReq, String user_id) {
        if (isNullOrEmpty(smsSalaryTaskReq.getSalaryTitle(), smsSalaryTaskReq.getSalaryMonth(),
                smsSalaryTaskReq.getIsHideZero(), smsSalaryTaskReq.getIsPublish(),
                smsSalaryTaskReq.getIsNotice())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (isNullOrEmpty(smsSalaryTaskReq.getDetailList()) || smsSalaryTaskReq.getDetailList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SALARY_DETAIL_LEAST_ONE);
        }

        if (isNullOrEmpty(smsSalaryTaskReq.getColumnList()) || smsSalaryTaskReq.getColumnList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SALARY_COLUMN_LEAST_ONE);
        }

        SmsSalaryDetailListCheckResp checkResp = checkSalaryDetailList(smsSalaryTaskReq.getDetailList());
        if (checkResp.getStatus().equals(CHECK_STATUS_ERROR)) {
            return CommonResult.failed(CommonCodeEnum.SALARY_DETAIL_ERROR);
        }

        //添加任务
        SmsSalaryTask smsSalaryTask = new SmsSalaryTask();
        BeanUtils.copyProperties(smsSalaryTaskReq, smsSalaryTask);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(smsSalaryTaskReq.getSalaryMonth());
        smsSalaryTask.setOnlyMonth(calendar.get(Calendar.MONTH) + 1);
        smsSalaryTask.setSalaryUserId(user_id);

        smsSalaryTaskMapper.insert(smsSalaryTask);
        String task_id = smsSalaryTask.getId();
        if (isNullOrEmpty(task_id)) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADD_FAIL));
        }

        //添加字段
        for (SmsSalaryColumnReq columnReq : smsSalaryTaskReq.getColumnList()) {
            if (isNullOrEmpty(columnReq.getColumnName(), columnReq.getIsDisplay())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            if (!columnReq.getIsDisplay().equals(DISPLAY_STATUS_FALSE) && !columnReq.getIsDisplay().equals(DISPLAY_STATUS_TRUE)) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }

            SmsSalaryColumn addSalaryColumn = new SmsSalaryColumn();
            addSalaryColumn.setColumnName(columnReq.getColumnName());
            addSalaryColumn.setIsDisplay(columnReq.getIsDisplay());
            addSalaryColumn.setTaskId(task_id);
            smsSalaryColumnMapper.insert(addSalaryColumn);

            columnReq.setId(addSalaryColumn.getId());
        }

        //添加详情
        for (SmsSalaryDetailCheckResp detailReq : checkResp.getList()) {
            SmsSalaryDetail addDetail = new SmsSalaryDetail();
            BeanUtils.copyProperties(detailReq, addDetail);

            addDetail.setTaskId(task_id);
            if (smsSalaryTaskReq.getIsPublish().equals(PUBLISH_STATUS_PUBLISH)) {
                addDetail.setPublishStatus(PUBLISH_STATUS_PUBLISH);
                addDetail.setPublishTime(new Date());
            } else {
                addDetail.setPublishStatus(PUBLISH_STATUS_NOT_PUBLISH);
            }

            smsSalaryDetailMapper.insert(addDetail);

            //添加详情对应字段内容
            int i = 0;
            for (BigDecimal content : detailReq.getValueList()) {
                SmsSalaryColumnContent addContent = new SmsSalaryColumnContent();
                addContent.setTaskId(task_id);
                addContent.setDetailId(addDetail.getId());
                addContent.setColumnId(smsSalaryTaskReq.getColumnList().get(i).getId());
                addContent.setContent(content == null ? BigDecimal.valueOf(0) : content);
                addContent.setColumnName(smsSalaryTaskReq.getColumnList().get(i).getColumnName());
                smsSalaryColumnContentMapper.insert(addContent);
                i++;
            }
        }

        //消息通知
        List<String> personList = checkResp.getList().stream().map(SmsSalaryDetailCheckResp::getUserId).collect(Collectors.toList());
        if (smsSalaryTaskReq.getIsNotice().equals(NOTICE_STATUS_TRUE)) {
            newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_MESSAGE,
                    user_id,
                    RangeTypeEnum.RANGE_TYPE_ENUM_PERSON,
                    personList,
                    AppTypeEnum.APP_TYPE_ENUM_SALARY,
                    task_id,
                    "",
                    "你有一条最新的工资单待查看",
                    TipsRecordStatusEnum.TIPS_RECORD_STATUS_ENUM_MESSAGE);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getSalaryTaskList(Integer pageNum, Integer pageSize, String user_id, String search_str) {
        QueryWrapper<SmsSalaryTask> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(search_str)) {
            queryWrapper.lambda().and(wrapper -> {
                wrapper.like(SmsSalaryTask::getSalaryTitle, search_str)
                        .or()
                        .eq(SmsSalaryTask::getOnlyMonth, search_str);
            });
        }
        queryWrapper.lambda()
                .orderByDesc(SmsSalaryTask::getCreateTime);
        Page<SmsSalaryTask> page = new Page<>(pageNum, pageSize);
        smsSalaryTaskMapper.selectPage(page, queryWrapper);
        List<SmsSalaryTaskResp> salaryTaskList = page.getRecords()
                .stream()
                .map(task -> {
                    SmsSalaryTaskResp smsSalaryTaskResp = new SmsSalaryTaskResp();
                    BeanUtils.copyProperties(task, smsSalaryTaskResp);

                    SmsUser smsUser = cacheUtil.getUserInfo(task.getSalaryUserId());
                    if (smsUser != null) {
                        SmsSearchUserResp smsSearchUserResp = new SmsSearchUserResp();
                        BeanUtils.copyProperties(smsUser, smsSearchUserResp);
                        smsSalaryTaskResp.setUserInfo(smsSearchUserResp);
                    }

                    //获取工资单详情
                    List<Map<String, Object>> mapList = smsSalaryDetailMapper.selectMaps(new QueryWrapper<SmsSalaryDetail>()
                            .select("count(*) as count , sum(actuality_salary) as sum")
                            .lambda()
                            .eq(SmsSalaryDetail::getTaskId, task.getId()));
                    Map<String, Object> salaryMap = mapList.get(0);
                    Long personLong = (Long) salaryMap.get("count");
                    BigDecimal salaryTotal = (BigDecimal) salaryMap.get("sum");
                    smsSalaryTaskResp.setPersonNum(personLong.intValue());
                    smsSalaryTaskResp.setSalaryTotal(salaryTotal);

                    Integer notPublishNum = smsSalaryDetailMapper.selectCount(new QueryWrapper<SmsSalaryDetail>()
                            .lambda()
                            .eq(SmsSalaryDetail::getTaskId, task.getId())
                            .eq(SmsSalaryDetail::getPublishStatus, PUBLISH_STATUS_NOT_PUBLISH));
                    smsSalaryTaskResp.setNotPublishNum(notPublishNum);

                    Integer publishNum = smsSalaryDetailMapper.selectCount(new QueryWrapper<SmsSalaryDetail>()
                            .lambda()
                            .eq(SmsSalaryDetail::getTaskId, task.getId())
                            .eq(SmsSalaryDetail::getPublishStatus, PUBLISH_STATUS_PUBLISH));
                    smsSalaryTaskResp.setPublishNum(publishNum);

                    Integer recallNum = smsSalaryDetailMapper.selectCount(new QueryWrapper<SmsSalaryDetail>()
                            .lambda()
                            .eq(SmsSalaryDetail::getTaskId, task.getId())
                            .eq(SmsSalaryDetail::getPublishStatus, PUBLISH_STATUS_RECALL));
                    smsSalaryTaskResp.setRecallNum(recallNum);

                    return smsSalaryTaskResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(salaryTaskList, total);
    }

    @Override
    public ResponseResult getSalaryTaskDetail(String task_id) {
        SmsSalaryTask smsSalaryTask = smsSalaryTaskMapper.selectById(task_id);
        if (smsSalaryTask == null) {
            return CommonResult.failed(CommonCodeEnum.SALARY_TASK_NOT_EXIST);
        }
        SmsSalaryTaskResp smsSalaryTaskResp = new SmsSalaryTaskResp();
        BeanUtils.copyProperties(smsSalaryTask, smsSalaryTaskResp);

        List<SmsSalaryColumnResp> columnRespList = smsSalaryColumnMapper.selectList(new QueryWrapper<SmsSalaryColumn>()
                        .lambda()
                        .eq(SmsSalaryColumn::getTaskId, task_id))
                .stream()
                .map(column -> {
                    SmsSalaryColumnResp smsSalaryColumnResp = new SmsSalaryColumnResp();
                    BeanUtils.copyProperties(column, smsSalaryColumnResp);
                    return smsSalaryColumnResp;
                })
                .collect(Collectors.toList());
        smsSalaryTaskResp.setColumnList(columnRespList);

        return CommonResult.success(smsSalaryTaskResp);
    }

    @Override
    @Transactional
    public ResponseResult updateSalaryTaskBasicInfo(SmsSalaryTaskReq smsSalaryTaskReq, String user_id) {
        if (isNullOrEmpty(smsSalaryTaskReq.getId(), smsSalaryTaskReq.getSalaryTitle(),
                smsSalaryTaskReq.getSalaryMonth())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsSalaryTask updateTask = new SmsSalaryTask();
        updateTask.setId(smsSalaryTaskReq.getId());
        updateTask.setSalaryTitle(smsSalaryTaskReq.getSalaryTitle());
        updateTask.setSalaryMonth(smsSalaryTaskReq.getSalaryMonth());

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(smsSalaryTaskReq.getSalaryMonth());
        updateTask.setOnlyMonth(calendar.get(Calendar.MONTH));

        smsSalaryTaskMapper.updateById(updateTask);
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult updateSalaryTaskPublishSetting(SmsSalaryTaskReq smsSalaryTaskReq, String user_id) {
        if (isNullOrEmpty(smsSalaryTaskReq.getId(), smsSalaryTaskReq.getIsHideZero())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (isNullOrEmpty(smsSalaryTaskReq.getColumnList()) || smsSalaryTaskReq.getColumnList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SALARY_COLUMN_LEAST_ONE);
        }

        SmsSalaryTask updateTask = new SmsSalaryTask();
        updateTask.setId(smsSalaryTaskReq.getId());
        updateTask.setIsHideZero(smsSalaryTaskReq.getIsHideZero());
        updateTask.setSalaryDescription(smsSalaryTaskReq.getSalaryDescription());
        smsSalaryTaskMapper.updateById(updateTask);

        for (SmsSalaryColumnReq columnReq : smsSalaryTaskReq.getColumnList()) {
            if (isNullOrEmpty(columnReq.getId())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }

            SmsSalaryColumn updateColumn = new SmsSalaryColumn();
            updateColumn.setId(columnReq.getId());
            updateColumn.setIsDisplay(columnReq.getIsDisplay());
            smsSalaryColumnMapper.updateById(updateColumn);
        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult deleteSalaryTask(SmsSalaryTaskReq smsSalaryTaskReq, String user_id) {
        if (isNullOrEmpty(smsSalaryTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String task_id = smsSalaryTaskReq.getId();
        ;

        smsSalaryTaskMapper.deleteById(task_id);

        smsSalaryDetailMapper.delete(new QueryWrapper<SmsSalaryDetail>()
                .lambda()
                .eq(SmsSalaryDetail::getTaskId, task_id));

        smsSalaryColumnMapper.delete(new QueryWrapper<SmsSalaryColumn>()
                .lambda()
                .eq(SmsSalaryColumn::getTaskId, task_id));

        smsSalaryColumnContentMapper.delete(new QueryWrapper<SmsSalaryColumnContent>()
                .lambda()
                .eq(SmsSalaryColumnContent::getTaskId, task_id));
        return CommonResult.success();
    }

    @Override
    public ResponseResult checkSalaryDetailList(SmsSalaryTaskReq smsSalaryTaskReq) {
        if (isNullOrEmpty(smsSalaryTaskReq.getDetailList()) || smsSalaryTaskReq.getDetailList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SALARY_DETAIL_LEAST_ONE);
        }
        SmsSalaryDetailListCheckResp checkResp = checkSalaryDetailList(smsSalaryTaskReq.getDetailList());
        return CommonResult.success(checkResp);
    }

    @Override
    public Future<ResponseResult> exportExamineHistoryList(SmsSalaryTaskReq smsSalaryTaskReq, HttpServletResponse response) {
        if (isNullOrEmpty(smsSalaryTaskReq.getId())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        try {
            SmsSalaryTask smsSalaryTask = smsSalaryTaskMapper.selectById(smsSalaryTaskReq.getId());
            if (isNullOrEmpty(smsSalaryTask)) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.SALARY_TASK_NOT_EXIST));
            }

            //获取动态字段
            List<SmsSalaryColumn> salaryColumnList = smsSalaryColumnMapper.selectList(new QueryWrapper<SmsSalaryColumn>()
                    .lambda()
                    .eq(SmsSalaryColumn::getTaskId, smsSalaryTaskReq.getId()));
            List<String> columnList = salaryColumnList.stream()
                    .map(SmsSalaryColumn::getColumnName)
                    .collect(Collectors.toList());

            //表头数据
            List<String> headerList = new ArrayList<>();
            headerList.add("姓名");
            headerList.add("身份证号");
            headerList.add("实发金额");
            if (!columnList.isEmpty()) {
                headerList.addAll(columnList);
            }

            //工资单数据
            List<SmsSalaryDetailExportResp> list = smsSalaryDetailMapper.selectList(new QueryWrapper<SmsSalaryDetail>()
                    .lambda()
                    .eq(SmsSalaryDetail::getTaskId, smsSalaryTaskReq.getId()))
                    .stream()
                    .map(detail->{
                        SmsSalaryDetailExportResp smsSalaryDetailResp = new SmsSalaryDetailExportResp();
                        BeanUtils.copyProperties(detail,smsSalaryDetailResp);

                        List<SmsSalaryColumnContent> contentList = smsSalaryColumnContentMapper.selectList(new QueryWrapper<SmsSalaryColumnContent>()
                                .lambda()
                                .eq(SmsSalaryColumnContent::getDetailId,detail.getId()));
                        smsSalaryDetailResp.setColumnList(contentList);
                        return smsSalaryDetailResp;
                    })
                    .collect(Collectors.toList());

            double sheetNum;
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (list != null && list.size() > 0) {
                sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);
                for (int k = 0; k < sheetNum; k++) {
                    //生成一个表格，设置表格名称为"资源导出表"
                    HSSFSheet sheet = workbook.createSheet(smsSalaryTask.getSalaryTitle() + (k + 1));

                    //设置表格列宽度为10个字节
                    sheet.setDefaultColumnWidth(12);
                    //创建标题的显示样式
                    HSSFCellStyle headerStyle = workbook.createCellStyle();
                    headerStyle.setFillForegroundColor(IndexedColors.YELLOW1.index);
                    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                    HSSFFont f = workbook.createFont();
                    f.setFontHeightInPoints((short) 10);//字号
                    f.setBold(true);//加粗
                    headerStyle.setFont(f);
                    //创建第一行表头
                    HSSFRow headrow = sheet.createRow(0);

                    //遍历添加表头
                    for (int i = 0; i < headerList.size() + 1; i++) {
                        //创建一个单元格
                        HSSFCell cell = headrow.createCell(i);

                        if (i == 0) {
                            //创建一个内容对象
                            HSSFRichTextString text = new HSSFRichTextString("序号");
                            //将内容对象的文字内容写入到单元格中
                            cell.setCellValue(text);
                            cell.setCellStyle(headerStyle);
                            continue;
                        }
                        //创建一个内容对象
                        String header1 = headerList.get(i-1);
                        HSSFRichTextString text = new HSSFRichTextString(header1);

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    int range = PER_SHEET_NUM;
                    if (k + 1 == sheetNum) {
                        range = list.size() - (PER_SHEET_NUM) * k;
                    }
                    for (int i = 0; i < range; i++) {
                        //创建一行
                        HSSFRow row1 = sheet.createRow(i + 1);
                        SmsSalaryDetailExportResp smsSalaryDetail = list.get((PER_SHEET_NUM) * k + i);
                        row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                        row1.createCell(1).setCellValue(new HSSFRichTextString(smsSalaryDetail.getName()));
                        row1.createCell(2).setCellValue(new HSSFRichTextString(smsSalaryDetail.getIdCard()));
                        row1.createCell(3).setCellValue(new HSSFRichTextString(smsSalaryDetail.getActualitySalary().toString()));
                       if (!columnList.isEmpty()){
                           List<SmsSalaryColumnContent> contentList = smsSalaryDetail.getColumnList();
                           for (int j = 0; j < columnList.size(); j++) {
                               String queryColumnID = salaryColumnList.get(j).getId();
                               List<SmsSalaryColumnContent> contentResultList = contentList.stream().filter(content-> content.getColumnId().equals(queryColumnID)).collect(Collectors.toList());
                               if (contentResultList.size()<1){
                                   break;
                               }
                               String rowContent = contentResultList.get(0).getContent().toString();
                               row1.createCell(j + 4).setCellValue(new HSSFRichTextString(rowContent));
                           }
                       }
                    }
                }
            }

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(smsSalaryTask.getSalaryTitle()+".xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode(smsSalaryTask.getSalaryTitle()+".xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return null;
    }

    private SmsSalaryDetailListCheckResp checkSalaryDetailList(List<SmsSalaryDetailReq> list) {
        AtomicReference<Integer> flag = new AtomicReference<>(1);
        AtomicReference<Integer> line_num = new AtomicReference<>(3);

        List<SmsSalaryDetailCheckResp> respList = list.stream()
                .map(detailReq -> {
                    SmsSalaryDetailCheckResp detailCheckResp = new SmsSalaryDetailCheckResp();
                    BeanUtils.copyProperties(detailReq, detailCheckResp);
                    detailCheckResp.setLineNum(line_num.get());
                    line_num.getAndSet(line_num.get() + 1);

                    if (isNullOrEmpty(detailReq.getName(), detailReq.getIdCard())) {
                        detailCheckResp.setStatus(CHECK_STATUS_ERROR);
                        detailCheckResp.setReason("请按要求填写姓名和身份证号");
                        flag.set(0);
                        return detailCheckResp;
                    }

                    List<SmsTeacherInfo> smsTeacherList = smsTeacherInfoMapper.selectList(new QueryWrapper<SmsTeacherInfo>()
                            .lambda()
                            .eq(SmsTeacherInfo::getTchName, detailReq.getName())
                            .eq(SmsTeacherInfo::getTchIdCard, detailReq.getIdCard()));
                    if (smsTeacherList == null || smsTeacherList.size() < 1) {
                        detailCheckResp.setStatus(CHECK_STATUS_ERROR);
                        detailCheckResp.setReason("查无此人，请核对用户数据");
                        flag.set(0);
                        return detailCheckResp;
                    }

                    SmsUserTeacherRelation smsUserTeacherRelation = smsUserTeacherRelationMapper.selectOne(new QueryWrapper<SmsUserTeacherRelation>()
                            .lambda()
                            .eq(SmsUserTeacherRelation::getTchId,smsTeacherList.get(0).getId()));
                    if (isNullOrEmpty(smsUserTeacherRelation)){
                        detailCheckResp.setStatus(CHECK_STATUS_ERROR);
                        detailCheckResp.setReason("用户不存在");
                        flag.set(0);
                        return detailCheckResp;
                    }

                    detailCheckResp.setUserId(smsUserTeacherRelation.getUserId());
                    detailCheckResp.setStatus(CHECK_STATUS_TRUE);

                    return detailCheckResp;
                })
                .sorted(Comparator.comparingInt(SmsSalaryDetailCheckResp::getStatus))
                .collect(Collectors.toList());
        SmsSalaryDetailListCheckResp checkResp = new SmsSalaryDetailListCheckResp();
        checkResp.setList(respList);
        checkResp.setStatus(flag.get());
        return checkResp;

    }
}
